package UserDb

import (
    "golang.org/x/crypto/bcrypt"
    "github.com/jmoiron/sqlx"
    "gitee.com/under-my-umbrella/gocode/db"
)

type User struct {
    UserId   int    `db:"user_id" json:"user_id"`
    Username string `db:"username" json:"username"`
    Password string `db:"password" json:"password"`
}

var database *sqlx.DB

func init() {
    database = db.GetDB()
}

// CheckUser 查询用户是否存在
func CheckUser(username string) bool {
    var user User
    query := "SELECT * FROM user WHERE username = ?"
    err := database.Get(&user, query, username)
    return err == nil
}

// GetUserByUsername 查询用户id
func GetUserIdByUsername(username string) (int, error) {
    var user User
    query := "SELECT * FROM user WHERE username = ?"
    err := database.Get(&user, query, username)
    if err != nil {
        return 0, err
    }
    return user.UserId, nil
}

// CreateUser 保存用户到数据库
func CreateUser(username string, password []byte) bool {
    query := "INSERT INTO user (username, password) VALUES (?, ?)"
    _, err := database.Exec(query, username, password)
    return err == nil
}

// GetUser 查询用户信息并验证密码
func GetUser(username string, password []byte) bool {
    var user User
    query := "SELECT * FROM user WHERE username = ?"
    err := database.Get(&user, query, username)
    if err != nil {
        return false
    }
    err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
    return err == nil
}
